package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsStorageMapper;
import com.qf.pojo.DtsStorage;
import com.qf.service.StorageService;
import com.qf.util.AliyunOSSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Random;

@Service
public class StorageServiceImpl implements StorageService {
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    @Autowired
    private DtsStorageMapper dtsStorageMapper;

    @Override
    public DtsStorage insert(String filename, String ext, long size, byte[] bytes)throws Exception {

        DtsStorage dtsStorage = new DtsStorage();
        dtsStorage.setName(filename);
        dtsStorage.setType(ext);


        String objectName = System.currentTimeMillis() + new Random().nextInt(100000) + "." + ext;
        dtsStorage.setKey(objectName);
        dtsStorage.setSize(Math.toIntExact(size));

        String url = AliyunOSSUtil.uploadImage(
                endpoint,
                accessKeyId,
                accessKeySecret,
                bucketName,
                objectName,
                bytes
        );


        dtsStorage.setUrl(url);
        dtsStorage.setAddTime(new Date());
        dtsStorage.setUpdateTime(new Date());
        dtsStorageMapper.insert(dtsStorage);
        return dtsStorage;
    }

    @Override
    public IPage findListByQuery(Integer page, Integer limit, String key, String name, String sort, String order) {
        return dtsStorageMapper.selectPage(new Page<>(page,limit),new QueryWrapper<DtsStorage>()
                .eq(!StringUtils.isEmpty(key),"'key'",key)
                .eq(!StringUtils.isEmpty(name),"name",name)
                .eq("deleted",false)
                .orderBy(!StringUtils.isEmpty(sort),"ASB".equalsIgnoreCase(order),sort));
    }

    @Override
    public void updateStorageName(DtsStorage dtsStorage) {
        dtsStorageMapper.updateById(dtsStorage);
    }
}
